//
//  HomePViewController.m
//  DimComDemo
//
//  Created by 于跃隆 on 2019/1/23.
//  Copyright © 2019 于跃隆. All rights reserved.
//

#import "HomePViewController.h"
#import "UIColor+ZXLazy.h"
#import "SDAutoLayout.h"
#import "NewPagedFlowView.h"
#import "PGIndexBannerSubiew.h"
#import "HomeModel.h"
#import "HomeShopM.h"
#import "BannerJumpViewController.h"

#define HCWidth [UIScreen mainScreen].bounds.size.width
#define HCHeight [UIScreen mainScreen].bounds.size.height


@interface HomePViewController ()<UITableViewDelegate , UITableViewDataSource , UIScrollViewDelegate , NewPagedFlowViewDelegate , NewPagedFlowViewDataSource>
//表格
@property (nonatomic , strong) UITableView *tbv;
//存放数据的可变数组
//第一个分区返回的数组
@property (nonatomic , strong) NSMutableArray *sectionSource1;
//第二个分区返回的数组
@property (nonatomic , strong) NSMutableArray *sectionSource2;
//第三个分区返回的数组
@property (nonatomic , strong) NSMutableArray *sectionSource3;
//下拉view
@property (nonatomic , strong) UIView *blackview;
//第二个下拉view
@property (nonatomic , strong) UIView *blackviewS;
//搜索条
@property (nonatomic , strong) UISearchBar *serC;

//网格
@property (nonatomic , strong) UICollectionView *collV;
//网格里的格子
@property (nonatomic , strong) UICollectionViewFlowLayout *collayout;
/**
 *  图片数组
 */
@property (nonatomic , strong) NSMutableArray *imageArray;
/**
 *  商品内容一数组
 */
@property (nonatomic , strong) NSMutableArray *ShopOneArray;
/**
 *  商品内容二数组
 */
@property (nonatomic , strong) NSMutableArray *ShopTwoArray;
/**
 *  商品内容三数组
 */
@property (nonatomic , strong) NSMutableArray *ShopThreeArray;
/**
 *  商品列表标题一热销新品
 */
@property (nonatomic , strong) NSString *hotShopNew;
/**
 *  商品列表标题二魔力时尚
 */
@property (nonatomic , strong) NSString *fashionShop;
/**
 *  商品列表标题三品质生活
 */
@property (nonatomic , strong) NSString *liveShop;


//定义model属性
@property (nonatomic , strong) BannerModel *bannerM;
@end

@implementation HomePViewController

//视图将要显示的时候
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //设置导航条颜色
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    //设置导航条状态
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加到视图上
    [self.view addSubview:self.tbv];
    //导航条UI
    [self addNavUI];
    //请求数据
    [self setAFNwork];
}
//导航条
-(void)addNavUI{
    //左侧view
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 15)];
    //导航左侧按钮
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 15)];
    //设置按钮点击事件
    [leftBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    //设置按钮背景图片
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"common_nav_btn_menu_n_hdpi"] forState:UIControlStateNormal];
    //把按钮添加到左侧view上
    [leftView addSubview:leftBtn];
    //把view 添加到导航条左侧
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    
    //右侧view
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 20)];
    //导航左侧按钮
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 20)];
    //设置按钮点击事件
    [rightBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
    //设置按钮背景图片
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"common_nav_btn_search_n_hdpi"] forState:UIControlStateNormal];
//    //设置按钮文字
//    [rightBtn setTitle:@"搜索" forState:UIControlStateNormal];
//    //设置文字大小
//    rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    //设置按钮颜色
    [rightBtn setTitleColor:[UIColor colorWithRed:103 green:103 blue:103] forState:UIControlStateNormal];
    //把按钮添加到左侧view上
    [rightView addSubview:rightBtn];
    //把view 添加到导航条左侧
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    
    //搜索条
    _serC = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, HCWidth - 100, 35)];
    //设置提示文字
    _serC.placeholder = @"请输入您要搜索的商品";
    //创建一个textfild
    UITextField *searchField  = [_serC valueForKey:@"searchField"];
    //修改背景颜色
    searchField.backgroundColor = [UIColor colorWithRed:242 green:242 blue:242];
    //改变圆角效果
    searchField.layer.cornerRadius = 17.5;
    searchField.layer.masksToBounds = YES;
    //添加到导航条上
    self.navigationItem.titleView = _serC;
    
    
    //创建滚动式图
    UIScrollView *BlackscV = [[UIScrollView alloc] init];
    //添加到blackview上
    [self.blackview addSubview:BlackscV];
    //设置位置
    BlackscV.sd_layout
    .topSpaceToView(_blackview, 0)
    .leftSpaceToView(_blackview, 0)
    .widthIs(HCWidth)
    .heightIs(60);
    //设置滚动代理
    BlackscV.delegate = self;
    //设置滚动范围
    BlackscV.contentSize = CGSizeMake(HCWidth * 1.3, 0);
    //设置bounces
    BlackscV.bounces = NO;
    //禁止水平和垂直滚动
    BlackscV.showsVerticalScrollIndicator = NO;
    BlackscV.showsHorizontalScrollIndicator = NO;
    
    //创建分段选择器
    UISegmentedControl *BlacksegC = [[UISegmentedControl alloc] initWithItems:@[@"男装",@"女装",@"女鞋",@"T恤",@"美妆护肤",@"手机数码"]];
    //隐藏下拉view
    self.blackview.hidden = YES;
    //添加到下拉view上
    [BlackscV addSubview:BlacksegC];
    //设置分段选择器位置
    BlacksegC.sd_layout
    .topSpaceToView(BlackscV, 15)
    .leftSpaceToView(BlackscV, 0)
    .widthIs(HCWidth-150)
    .heightIs(30);
    //设置大小
//    BlacksegC.backgroundColor = [UIColor greenColor];
    //按照内存适应宽度
//    [BlacksegC setApportionsSegmentWidthsByContent:YES];
    //取消边框颜色
    BlacksegC.tintColor = [UIColor clearColor];
    //设置默认选中
    BlacksegC.selectedSegmentIndex = 0;
    // 正常状态下
    NSDictionary * normalTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:17.0f],NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#ffffff"]};
    [BlacksegC setTitleTextAttributes:normalTextAttributes forState:UIControlStateNormal];
    
    // 选中状态下
    NSDictionary * selctedTextAttributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:17.0f],NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#ff5f71"]};
    [BlacksegC setTitleTextAttributes:selctedTextAttributes forState:UIControlStateSelected];
    
    //设置分段控制器事件
    [BlacksegC addTarget:self action:@selector(SegMentclick:) forControlEvents:UIControlEventValueChanged];
    
    //隐藏view
    self.blackviewS.hidden = YES;
    //添加view
    [self.view addSubview:self.blackviewS];
}
//点击视图取消响应
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //取消第一响应
    [_serC resignFirstResponder];
}
//请求
-(void)setAFNwork{
    //初始化
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    //拼接网络接口
    NSString *UrlStr = [interface stringByAppendingString:Homebanner];
    //GET请求
    [manager GET:UrlStr parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //创建model
        HomeModel *model = [HomeModel yy_modelWithJSON:responseObject];
        //把model赋值给数组
        self.imageArray = model.result;
        
        NSLog(@"model:%@",self.imageArray);
        
        NSLog(@"%@",responseObject);

        [self performSelectorOnMainThread:@selector(TopView) withObject:nil waitUntilDone:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
    
    //商品url
    NSString *ShopUrl = [interface stringByAppendingString:HomeShop];
    //GET请求
    [manager GET:ShopUrl parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //创建商品model
        HomeShopM *model = [HomeShopM yy_modelWithJSON:responseObject];
        //取model里的model.result
        ShopAny *any = model.result;
        int i=0;
        //取数组第0个元素
        ShopOneA *oneM = any.rxxp[i];
        ShopOneA *twoM = any.mlss[i];
        ShopOneA *threeM = any.pzsh[i];
        //把每个标题给每个字符串
        self.hotShopNew = oneM.name;
        self.fashionShop = twoM.name;
        self.liveShop = threeM.name;
        NSLog(@"oneM:%@",oneM);
        //取数组里面的东西
        ShopOne *one = oneM.commodityList;
        ShopOne *two = twoM.commodityList;
        ShopOne *three = threeM.commodityList;
        //把model取出的值添加到数组里
        self.ShopOneArray = one;
        self.ShopTwoArray = two;
        self.ShopThreeArray = three;
        NSLog(@"one:%@",one);
        
        
        
        NSLog(@"Shop:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
}
//分段控制器点击事件
-(void)SegMentclick:(UISegmentedControl *)seg{
    //每个默认选中
    NSInteger selectedIndex = seg.selectedSegmentIndex;
    NSLog(@"%ld",selectedIndex);
    
    //创建滚动式图
    UIScrollView *BlackscV = [[UIScrollView alloc] init];
    //添加到blackview上
    [self.blackview addSubview:BlackscV];
    //设置位置
    BlackscV.sd_layout
    .topSpaceToView(_blackviewS, 0)
    .leftSpaceToView(_blackviewS, 0)
    .widthIs(HCWidth)
    .heightIs(100);
    //设置滚动代理
    BlackscV.delegate = self;
    //设置滚动范围
    BlackscV.contentSize = CGSizeMake(HCWidth * 1.3, 0);
    //设置bounces
    BlackscV.bounces = NO;
    //禁止水平和垂直滚动
    BlackscV.showsVerticalScrollIndicator = NO;
    BlackscV.showsHorizontalScrollIndicator = NO;
    //用switch判断每个item
    switch (selectedIndex) {
        case 0:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            //用for循环加入每个东西
            
            break;
        case 1:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            break;
        case 2:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            break;
        case 3:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            break;
        case 4:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            break;
        case 5:
            //判断点击状态
            if (seg.selectedSegmentIndex == selectedIndex) {
                //隐藏view
                self.blackviewS.hidden = NO;
                //btn状态
                
            }
            break;
        default:
            //隐藏view
            self.blackviewS.hidden = NO;
            NSLog(@"nono");
            break;
    }
}
//左侧按钮事件
-(void)LeftClick:(UIButton *)btn{
    //判断点击状态
    if (btn.selected == YES) {
        //隐藏view
        self.blackview.hidden = YES;
        self.blackviewS.hidden = YES;
        //btn状态
        btn.selected = NO;
    }else{
        //隐藏view
        self.blackview.hidden = NO;
        self.blackviewS.hidden = NO;
        //btn状态
        btn.selected = YES;
    }
    
}
//右侧按钮事件
-(void)RightClick:(UIButton *)btn{
    
}
//慵懒加载来初始化表格
-(UITableView *)tbv{
    if (!_tbv) {
        //初始化
        _tbv = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        //设置代理和数据源
        _tbv.delegate = self;
        _tbv.dataSource = self;
        //取消分割线
        _tbv.separatorColor = [UIColor whiteColor];
    }
    return _tbv;
}
//返回分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
//返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *oj = @"cell";
    //初始化
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
    }
    //判断每个分区的东西
    if (indexPath.section == 0) {
        //设置行高
        _tbv.rowHeight = 260;
        
        
    }else if (indexPath.section == 1){
        //设置行高
        _tbv.rowHeight = 200;
        
    }else{
        //设置行高
        _tbv.rowHeight = 320;
        
    }
    
    return cell;
}
-(void)TopView{
    //轮播图
    NewPagedFlowView *pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, 8, HCWidth, 200)];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.1;
    pageFlowView.isCarousel = YES;
    pageFlowView.orientation = NewPagedFlowViewOrientationHorizontal;
//    pageFlowView.orginPageCount = self.imageArray.count;
    pageFlowView.isOpenAutoScroll = YES;
    pageFlowView.backgroundColor = [UIColor whiteColor];
    
    //初始化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, pageFlowView.frame.size.height - 32, HCWidth, 8)];
    pageFlowView.pageControl = pageControl;
    [pageFlowView addSubview:pageControl];
    //滚动式图
    UIScrollView *bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 8, HCWidth, 200)];
    [bottomScrollView addSubview:pageFlowView];
    
    [pageFlowView reloadData];
    
    //添加到表格头视图上
    self.tbv.tableHeaderView = bottomScrollView;
    self.tbv.tableHeaderView.backgroundColor = [UIColor whiteColor];
    
    
}
//取消表格顶部view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
//取消头视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
//表格点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ///取消点击动画效果
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    //取消第一响应
    [_serC resignFirstResponder];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    return CGSizeMake(HCWidth - 60, 200);
}
- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    //bannerModel用来接收数组内容
    _bannerM = self.imageArray[subIndex];
    //跳转控制器
    BannerJumpViewController *Jump = [[BannerJumpViewController alloc] init];
    //把属性给下个跳转界面
    Jump.Bannerlink = _bannerM.jumpUrl;
    //取消tabbar
    Jump.hidesBottomBarWhenPushed = YES;
    //设置返回按钮
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];
    //设置返回按钮颜色
    self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];
    //跳转
    [self.navigationController pushViewController:Jump animated:YES];
    
    
    NSLog(@"点击了第%ld张图",(long)subIndex + 1);
}
//返回的滚动式图个数
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    
    return self.imageArray.count;
}
//设置轮播图里面你的view
- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 0, HCWidth, 200)];
        bannerView.tag = index;
        bannerView.layer.cornerRadius = 4;
        bannerView.layer.masksToBounds = YES;
    }
    _bannerM = self.imageArray[index];
    //在这里下载网络图片
    [bannerView.mainImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", _bannerM.imageUrl]]];
//    bannerView.mainImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_bannerM.imageUrl]]];
    
//    bannerView.mainImageView.image = [UIImage imageNamed:_bannerM.imageUrl];
    
    return bannerView;
}
- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    
    NSLog(@"ViewController 滚动到了第%ld页",pageNumber);
    
}
//初始化图片数组
-(NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc] init];
    }
    return _imageArray;
}
//初始化商品数组
-(NSMutableArray *)ShopOneArray{
    if (!_ShopOneArray) {
        _ShopOneArray = [[NSMutableArray alloc] init];
    }
    return _ShopOneArray;
}
//初始化商品数组
-(NSMutableArray *)ShopTwoArray{
    if (!_ShopTwoArray) {
        _ShopTwoArray = [[NSMutableArray alloc] init];
    }
    return _ShopTwoArray;
}
//初始化商品数组
-(NSMutableArray *)ShopThreeArray{
    if (!_ShopThreeArray) {
        _ShopThreeArray = [[NSMutableArray alloc] init];
    }
    return _ShopThreeArray;
}
//初始化下拉view
-(UIView *)blackview{
    if (!_blackview) {
        //初始化
        _blackview = [[UIView alloc] init];
        //添加到视图上
        [self.view addSubview:_blackview];
        
        //设置view的位置
        _blackview.sd_layout
        .leftSpaceToView(self.view, 0)
        .topSpaceToView(self.view, 70)
        .widthIs(HCWidth)
        .heightIs(60);
        //设置view背景颜色
        _blackview.backgroundColor = [UIColor blackColor];
        //设置透明度
        _blackview.alpha = 0.7;
    }
    return _blackview;
}
//初始化下拉view
-(UIView *)blackviewS{
    if (!_blackviewS) {
        //初始化
        _blackviewS = [[UIView alloc] init];
        //添加到视图上
        [self.view addSubview:_blackviewS];
        
        //设置view的位置
        _blackviewS.sd_layout
        .leftSpaceToView(self.view, 0)
        .topSpaceToView(self.view, 130)
        .widthIs(HCWidth)
        .heightIs(100);
        //设置view背景颜色
        _blackviewS.backgroundColor = [UIColor colorWithHexString:@"#5d5d5d"];
        //设置透明度
        _blackviewS.alpha = 0.7;
    }
    return _blackviewS;
}


@end
